package com.begamer.card.model.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.begamer.card.model.pojo.Privilege;

public class PrivilegeDao extends HibernateDaoSupport {

	private static final Log log = LogFactory.getLog(PrivilegeDao.class);

	public void save(Privilege privilege)
	{
		log.debug("saving Privilege instance");
		try
		{
			getHibernateTemplate().save(privilege);
			log.debug("save successful");
		}
		catch (RuntimeException e)
		{
			log.error("save failed" + e);
			throw e;
		}
	}

	public void delete(Privilege privilege)
	{
		log.debug("deleting Privilege instance");
		try
		{
			getHibernateTemplate().delete(privilege);
			log.debug("delete successful");
		}
		catch (RuntimeException e)
		{
			log.error("delete failed" + e);
			throw e;
		}
	}

	public void merge(Privilege privilege)
	{
		log.debug("merging Privilege instance");
		try
		{
			getHibernateTemplate().merge(privilege);
			log.debug("merger Privilege successful");
		}
		catch (RuntimeException e)
		{
			log.error("merger Privilege failed" + e);
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Privilege> find()
	{
		log.debug("finding All Privilege instance");
		try
		{
			String queryString = "from Privilege p";
			return getHibernateTemplate().find(queryString);
		}
		catch (RuntimeException e)
		{
			log.error("find All failed" + e); 
			throw e;
		}
	}

	public Privilege findOne(int id)
	{
		log.debug("finding One Privilege By Id instance");
		try
		{
			Privilege privilege = (Privilege) getHibernateTemplate().get(
					Privilege.class, id);
			log.debug("finding One Privilege successful");
			return privilege;
		}
		catch (RuntimeException e)
		{
			log.error("find One Privilege failed");
			throw e;
		}
	}

	/** *****根据GM编号查询权限****** */
	@SuppressWarnings("unchecked")
	public List<Privilege> getPrivilegeByManagerId(int managerId)
	{
		Session session = getSession();
		try
		{
			Query query = session
					.createQuery("from Privilege p where p.masterValue=?");
			query.setInteger(0, managerId);
			List<Privilege> list = query.list();

			return list;
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	/** *****根据GM编号和模板编号查询权限****** */
	@SuppressWarnings("unchecked")
	public int getPrivilegeByManagerId(int managerId,int accessId)
	{
		Session session = getSession();
		try
		{
			Query query = session.createQuery("from Privilege p where p.masterValue=? and p.accessValue=?");
			query.setInteger(0, managerId);
			query.setInteger(1, accessId);
			List<Privilege> list = query.list();
			return list.size();
		}
		catch (RuntimeException e)
		{
			throw e;
		}
		finally
		{
			session.close();
		}
	}
}
